package com.knowledge.plus.io.BIO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * BIO(同步阻塞IO)服务端（支持多客户端连接）
 *
 * @author TPF
 * @since 2025/6/4
 */
public class BioServer {
    public static void main(String[] args) throws IOException {
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("BIO服务端启动，端口:8080");

            while (true) {
                // 阻塞点1：等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端接入: " + clientSocket.getRemoteSocketAddress());

                // 为每个连接创建独立线程
                new Thread(() -> handleClient(clientSocket)).start();
            }
        }
    }

    private static void handleClient(Socket socket) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)) {

            String request;
            // 阻塞点2：等待客户端发送数据
            while ((request = reader.readLine()) != null) {
                System.out.println("收到消息: " + request);
                // 回写响应
                writer.println("服务端响应: " + request.toUpperCase());
            }
        } catch (IOException e) {
            System.out.println("客户端断开: " + socket.getRemoteSocketAddress());
        }
    }
}